package com.example.demo.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MsgConfiguration {
    //延时交换机
    public static final String DELAY_EXCHANGE = "spring.boot.delay.exchange";//
    //死信交换机
    public static final String DLX_EXCHANGE = "spring.boot.dlx.exchange";

    //延时队列
    public static final String DELAY_QUEUE="spring.boot.delay.queue";
    //死信队列
    public static final String DLX_QUEUE="spring.boot.dlx.queue";
    //延时队列routingkey
    public static final String DELAY_ROUTING_KEY="spring.boot.delay.routingkey";
    //死信队列routingkey
    public static final String DLX_ROUTING_KEY="spring.boot.dlx.routingkey";

    //延时交换机
    @Bean("delayExchange")
    public DirectExchange directExchange(){
        return new DirectExchange(DELAY_EXCHANGE);
    }
    //死信交换机
    @Bean("dlxExchange")
    public DirectExchange dlxExchange(){
        return new DirectExchange(DLX_EXCHANGE);
    }
    //死信队列
    @Bean("dlxQueue")
    public Queue dlxQueue(){
        return new Queue(DLX_QUEUE);
    }
    //延时队列
    @Bean("delayQueue")
    public Queue delayQueue(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange",DLX_EXCHANGE);//设置死信交换机名称
        map.put("x-dead-letter-routing-key",DLX_ROUTING_KEY);//设置死信队列routingkey
        map.put("x-message-ttl",30000);//设置延时时间
        return QueueBuilder.durable(DELAY_QUEUE).withArguments(map).build();
    }

    //死信队列绑定
    @Bean
    public Binding dalayBinding(@Qualifier("dlxQueue") Queue queue,
                                @Qualifier("dlxExchange") DirectExchange directExchange){
        return BindingBuilder.bind(queue).to(directExchange).with(DLX_ROUTING_KEY);
    }

    //延时队列绑定
    @Bean
    public Binding dlxBinding(@Qualifier("delayQueue") Queue queue,
                              @Qualifier("delayExchange") DirectExchange directExchange){
        return BindingBuilder.bind(queue).to(directExchange).with(DELAY_ROUTING_KEY);
    }
}
